﻿using UnityEngine;
using System.Collections;

public class NGUI_ParticleScaleV2 : MonoBehaviour 
{
    public UIRoot uiRoot;
    public ParticleSystemRenderer pRenderer;
    public Material dyMaterial;
    public Camera target;

    void OnEnable()
    {
        pRenderer = GetComponent<ParticleSystemRenderer>();
        dyMaterial = pRenderer.material;
        if (pRenderer.renderMode == ParticleSystemRenderMode.Mesh){
            dyMaterial.EnableKeyword("SCALE_ON_MESH");
        }
        else {
            dyMaterial.EnableKeyword("SCALE_ON_Bill");
        }
        

        target = NGUITools.FindCameraForLayer(gameObject.layer);

        uiRoot = NGUITools.FindInParents<UIRoot>(gameObject);
    }

    void OnWillRenderObject()
    {
        if (target != null && uiRoot != null)
        {
            if (pRenderer.renderMode != ParticleSystemRenderMode.Mesh)
            {
                Vector3 cameraPos = target.worldToCameraMatrix.MultiplyPoint(transform.position);
                dyMaterial.SetVector(Shader.PropertyToID("_Position"), cameraPos);
            }
            
            float scale = 648.0f / uiRoot.manualHeight ; //must set FixedSize size
            dyMaterial.SetVector(Shader.PropertyToID("_Scale"), Vector3.one * scale);
        }
    }

    void OnDisable()
    {
        if (pRenderer.renderMode == ParticleSystemRenderMode.Mesh) {
            dyMaterial.EnableKeyword("SCALE_ON_MESH");
        }
        else {
            dyMaterial.EnableKeyword("SCALE_ON_Bill");
        }
    }
}
